<template>
  <div :class="isOnDedicatedScreen ? 'screen-container' : 'embedded-container'">
    <div class="data-screen-wrapper" ref="screenRef">
      <DataScreenHeader @toggle="handleToggle" />
      <div class="main-content">
        <!-- 左栏: 聚焦资产和物 -->
        <div class="left-column">
          <DataPanel title="资产信息" class="panel-item" :is-loading="isLoading">
            <ProjectInfoPanel :stats="overviewStats.asset_stats" />
          </DataPanel>
          <DataPanel title="人员入驻情况" class="panel-item" :is-loading="isLoading">
             <OccupancyPanel :stats="overviewStats.people_stats" :unit-data="unitStatusData" />
          </DataPanel>
          <DataPanel title="园区通知公告" class="panel-item" :is-loading="isLoading">
             <NotificationList :notifications="notificationList" />
          </DataPanel>
          <DataPanel title="车位使用情况" class="panel-item" :is-loading="isLoading">
            <ParkingStatsPanel :stats="overviewStats.parking_stats" />
          </DataPanel>
        </div>
        <!-- 中栏 -->
        <div class="center-column">
          <div class="kpi-panel">
            <KpiDonut :data="kpiData" :is-loading="isLoading" />
          </div>
          <DataPanel title="园区建设与招商概览" class="panel-item" :is-loading="isLoading">
            <ParkCoreAnalysis 
              :building-data="buildingStatusData"
              :investment-data="investmentTrendData"
              :theme="chartTheme"
            />
          </DataPanel>
        </div>
        <!-- 右栏: 聚焦人和服务 -->
        <div class="right-column">
          <DataPanel title="楼宇租售情况(面积/㎡)" class="panel-item" :is-loading="isLoading">
            <SalesLeasingPanel :stats="salesLeasingData" />
          </DataPanel>
          <DataPanel title="访客统计" class="panel-item" :is-loading="isLoading">
            <VisitorStatsPanel :stats="overviewStats.people_stats?.visitors" />
          </DataPanel>
          <DataPanel title="入驻企业类型分布" class="panel-item" :is-loading="isLoading">
            <PieChart :chart-data="companyTypeData" :theme="chartTheme" />
          </DataPanel>
          <DataPanel title="重点设备故障率 (TOP 5)" class="panel-item" :is-loading="isLoading">
            <BarChart :chart-data="repairHotspotsData" :theme="chartTheme" />
          </DataPanel>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import DataScreenHeader from './components/DataScreenHeader.vue';
import DataPanel from './components/DataPanel.vue';
import OccupancyPanel from './components/OccupancyPanel.vue';
import ProjectInfoPanel from './components/ProjectInfoPanel.vue';
import PieChart from './components/PieChart.vue';
import LineChart from './components/LineChart.vue';
import BarChart from './components/BarChart.vue';
import KpiDonut from './components/KpiDonut.vue';
import ChinaMap from './components/ChinaMap.vue';
import ParkingStatsPanel from './components/ParkingStatsPanel.vue';
import VisitorStatsPanel from './components/VisitorStatsPanel.vue';
import ParkCoreAnalysis from './components/ParkCoreAnalysis.vue';
import NotificationList from './components/NotificationList.vue';
import SalesLeasingPanel from './components/SalesLeasingPanel.vue';

import {
  getOverviewStats,
  getUnitStatusDistribution,
  getContractGrowthTrend,
  getCompanyTypeDistribution,
  getRepairHotspots,
  getBuildingStatus,
  getInvestmentTrend,
  getNotifications,
  getAssetSalesLeasing,
} from '@/api/analytics';

const screenRef = ref(null);
const route = useRoute();
const router = useRouter();

const isOnDedicatedScreen = computed(() => route.path === '/data-screen');

// 全局加载状态
const isLoading = ref(true);

const handleResize = () => {
  if (screenRef.value) {
    const designWidth = 1920;
    const designHeight = 1080;
    const scale = Math.min(
      window.innerWidth / designWidth,
      window.innerHeight / designHeight
    );
    screenRef.value.style.transform = `translate(-50%, -50%) scale(${scale})`;
  }
};

const handleToggle = () => {
  if (isOnDedicatedScreen.value) {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen();
    } else if (document.exitFullscreen) {
      document.exitFullscreen();
    }
  } else {
    window.open(router.resolve({ name: 'DataScreenFullscreen' }).href, '_blank');
  }
};

onMounted(() => {
  if (isOnDedicatedScreen.value) {
      window.addEventListener('resize', handleResize);
      handleResize();
  }
  fetchData();
});

onUnmounted(() => {
  if (isOnDedicatedScreen.value) {
    window.removeEventListener('resize', handleResize);
  }
});

const chartTheme = 'dark';

const overviewStats = ref({ 
    asset_stats: {}, 
    people_stats: { employees: {}, visitors: {} }, 
    service_stats: { breakdown: {} }, 
    finance_stats: {},
    parking_stats: {}
});
const unitStatusData = ref([]);
const contractTrendData = ref({});
const companyTypeData = ref([]);
const repairHotspotsData = ref({});
const buildingStatusData = ref([]);
const investmentTrendData = ref([]);
const notificationList = ref([]);
const salesLeasingData = ref({});

const kpiData = computed(() => {
    if (!overviewStats.value.finance_stats || 
        !overviewStats.value.people_stats || 
        !overviewStats.value.asset_stats || 
        !salesLeasingData.value) {
        return [];
    }
    
    // 1. 楼宇利用率
    const totalArea = salesLeasingData.value.total_area || 0;
    const usedArea = (salesLeasingData.value.sold_area || 0) + (salesLeasingData.value.leased_area || 0);
    const buildingUsageRate = totalArea > 0 ? ((usedArea / totalArea) * 100).toFixed(1) : '0.0';
    
    // 2. 本月总收入
    const monthlyRevenue = parseFloat(overviewStats.value.finance_stats.monthly_revenue?.replace(/,/g, '')) || 0;
    
    // 3. 入驻企业
    const companies = overviewStats.value.people_stats.companies || 0;

    return [
        { title: '楼宇利用率(%)', value: buildingUsageRate, color: '#00e5ff'},
        { title: '本月总收入(万元)', value: monthlyRevenue.toFixed(2), color: '#ffc53d'},
        { title: '入驻企业(家)', value: companies, color: '#aa00ff'},
    ]
});

const fetchData = async () => {
  try {
    isLoading.value = true; // 开始获取数据时，设置加载状态为true
    const [
      overviewRes,
      unitStatusRes,
      contractTrendRes,
      companyTypeRes,
      repairHotspotsRes,
      buildingStatusRes,
      investmentTrendRes,
      notificationListRes,
      salesLeasingRes,
    ] = await Promise.all([
      getOverviewStats(),
      getUnitStatusDistribution(),
      getContractGrowthTrend(),
      getCompanyTypeDistribution(),
      getRepairHotspots(),
      getBuildingStatus(),
      getInvestmentTrend(),
      getNotifications(),
      getAssetSalesLeasing(),
    ]);

    console.log('从后端获取的园区综合运营总览核心指标:', overviewRes.data);

    overviewStats.value = overviewRes.data;
    unitStatusData.value = unitStatusRes.data;

    contractTrendData.value = {
        labels: contractTrendRes.data.map(item => item.month),
        values: contractTrendRes.data.map(item => item.count)
    };

    companyTypeData.value = companyTypeRes.data;

    // 处理设备故障率数据，计算百分比并排序
    const repairData = repairHotspotsRes.data.map(item => ({
      name: item.name,
      value: ((item.value / Math.max(...repairHotspotsRes.data.map(d => d.value))) * 100).toFixed(1)
    }));
    
    // 按故障率从高到低排序
    repairData.sort((a, b) => b.value - a.value);
    
    // 只取前5项，避免图表过于拥挤
    const topRepairData = repairData.slice(0, 5);
    
    repairHotspotsData.value = {
      labels: topRepairData.map(item => item.name),
      values: topRepairData.map(item => parseFloat(item.value))
    };

    buildingStatusData.value = buildingStatusRes.data;
    investmentTrendData.value = {
      labels: investmentTrendRes.data.map(item => item.month),
      values: investmentTrendRes.data.map(item => item.count)
    };

    notificationList.value = notificationListRes.data;
    salesLeasingData.value = salesLeasingRes.data;

  } catch (error) {
    console.error("Failed to fetch dashboard data:", error);
  } finally {
    isLoading.value = false; // 数据获取完成（无论成功或失败），设置加载状态为false
  }
};
</script>

<style scoped>
/* --- Layout Containers --- */
.embedded-container {
    width: 100%;
    height: 100%;
}
.screen-container {
    position: relative;
    width: 100vw;
    height: 100vh;
    background: #000;
    overflow: hidden;
}

/* --- Base Wrapper Style --- */
.data-screen-wrapper {
    display: flex;
    flex-direction: column;
    background-image: url('@/assets/images/screen-bg4.png');
    background-size: cover;
    background-position: center;
    color: #fff;
    overflow: hidden;
}

/* --- Mode-Specific Wrapper Styles --- */
.embedded-container .data-screen-wrapper {
    height: 100%; /* Fit parent in admin layout */
}
.screen-container .data-screen-wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 1920px;
    height: 1080px;
    transform-origin: center;
    transition: transform 0.3s ease;
}

/* --- Grid Layout --- */
.main-content {
    flex-grow: 1;
    display: grid;
    grid-template-columns: 480px 1fr 480px;
    gap: 20px;
    padding: 20px;
    height: calc(100% - 80px);
}

.left-column, .right-column {
    display: grid;
    gap: 20px;
    /* 
      使用 1fr 单位替代 calc()。
      1fr 是一个弹性单位，代表网格容器中可用空间的一等份。
      这比手动计算更健壮，能更好地适应复杂的布局和不同的屏幕尺寸，
      自动处理空间的分割，从根本上解决溢出问题。
    */
    grid-template-rows: repeat(4, 1fr);
    min-height: 0; /* 新增：强制列遵守父级分配的高度，防止其内容撑破布局 */
}
.center-column {
    display: grid;
    gap: 20px;
    grid-template-rows: auto 1fr;
}

.kpi-panel {
    background: rgba(0, 21, 53, 0.5);
    padding: 15px;
    border: 1px solid #005c9e;
}

.map-panel {
    :deep(.panel-body) {
        padding: 0;
    }
}

.panel-item {
  min-height: 0;
}

.task-breakdown-stats, .finance-stats {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 20px;
  height: 100%;
}
.task-item, .finance-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #aed4ff;
  background: rgba(0, 162, 255, 0.1);
  padding: 10px 15px;
  border-radius: 4px;
}
.task-item strong, .finance-item strong {
  font-size: 20px;
  font-weight: bold;
  color: #fff;
}

.people-overview-stats, .visitor-stats {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 20px;
  height: 100%;
}
.people-item, .visitor-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #aed4ff;
  background: rgba(0, 162, 255, 0.1);
  padding: 15px;
  border-radius: 4px;
}
.people-item strong, .visitor-item strong {
  font-size: 22px;
  font-weight: bold;
  color: #fff;
}
</style> 